<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Workflow extends BaseController {

    private $processLoop = 0;

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 用户类型判断
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载库
        $this->load->model('workflowModel');
        $this->load->model('schoolModel');
    }

    // 流程设计
    public function process(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "process");
    }
    // 获取流程列表
    public function get_process_list(){
        // 过滤正常的状态
        $state = $this->get('state');
        if(isset($state) && 'normal' === $state){
            $totalParams['state'] = 'normal';
            $data['state'] = 'normal';
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->workflowModel->get_workflow_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $gradeList = $this->workflowModel->get_workflow_list($data);
        // 返回值
        exit(admin_table_data($total, $gradeList));
    }

    // 保存工作流
    public function save_process_action(){
        $processId = $this->post("id");
        $workflowTitle = $this->post("workflow_title");
        // 数据检查
        if(!$workflowTitle) throw new Exception("请填写工作流名称");
        // 入库
        $data['workflow_title'] = $workflowTitle;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($processId) {
             $this->db->update(WorkflowModel::$workflowTable, $data,"id='{$processId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(WorkflowModel::$workflowTable, $data);
        }
        $msg = $processId ? '修改工作流成功' : '添加工作流成功';
        exit(json($msg, true));
    }

    // 编辑工作流表单
    public function edit_process_form($workflowId){
        $this->workflowInfo = $workflowInfo = $this->workflowModel->get_workflow_info($workflowId);
        if($workflowInfo['school_id'] != $this->rmxSchool['id'] || $workflowInfo['campus_id'] != $this->campusInfo['id']) show_error("工作流不存在，请刷新后重试");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "process_form");
    }

    // 提交表单结构
    public function save_workflow_form() {
        $workflowId = $this->post("workflow");
        $workflowForm = $this->post("workflow_form");
        // 获取工作流
        $workflowInfo = $this->workflowModel->get_workflow_info($workflowId);
        if($workflowInfo['school_id'] != $this->rmxSchool['id'] || $workflowInfo['campus_id'] != $this->campusInfo['id']) show_error("工作流不存在，请刷新后重试");
        if(!$workflowForm) throw new Exception("表单内容不能为空，请重新提交");
        // 检查表单内容
        foreach($workflowForm as $itemId => $item) {
            // 表单内容项检查
            switch($item['type']) {
                case 'workflow-select':
                    if(!$item['selectOptions']) throw new Exception("下拉框内容不能为空");
                    break;
            }
        }

        // 表单内容入库
        $save['workflow_form'] = json_encode($workflowForm, JSON_UNESCAPED_UNICODE);
        $this->db->update(WorkflowModel::$workflowTable, $save, "id='{$workflowId}'");

        exit(json("保存工作流表单成功", true));
    }

    // 编辑工作流
    public function edit_process($workflowId){
        $this->workflowInfo = $workflowInfo = $this->workflowModel->get_workflow_info($workflowId);
        if($workflowInfo['school_id'] != $this->rmxSchool['id'] || $workflowInfo['campus_id'] != $this->campusInfo['id']) show_error("工作流不存在，请刷新后重试");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "process_degisn");
    }
    // 提交工作流流程
    public function save_workflow_process(){
        $workflowId = $this->post("workflow");
        $workflowProcess = $this->post("workflow_process");
        // 检查流程
        $this->check_workflow_process('start', $workflowProcess);

        // 保存审批流程
        $save['workflow_process'] = json_encode($workflowProcess, JSON_UNESCAPED_UNICODE);
        $this->db->update(WorkflowModel::$workflowTable, $save, "id='{$workflowId}'");

        exit(json("流程保存成功", true));
    }
    // 检查工作流流程
    private function check_workflow_process($nodeKey, $processData) {
        if($this->processLoop >= 100) throw new Exception("工作流流程进入死循环，保存失败");
        // 如果是结束节点，就可以退出了
        if($nodeKey == 'end') return;

        // 检查节点是否存在
        if(!isset($processData[$nodeKey])) {
            if($nodeKey == 'start') throw new Exception("流程缺少开始节点，保存失败");
            if($nodeKey == 'end') throw new Exception("流程缺少结束节点，保存失败");
        }

        // 节点数据
        $nodeData = $processData[$nodeKey];
        // 检查是否有节点连接
        if(!isset($nodeData['links']) || count($nodeData['links']) == 0) throw new Exception("节点缺少外部连接，保存失败");
        // 检查是否有同意节点连接
        $nextNode = "";
        $nodeLinks = $nodeData['links'];
        foreach($nodeLinks as $connId => $link) {
            
            if($link['result'] == 'pass' || $link['result'] == 'start') $nextNode = $link['target'];
            // 检查开始节点的下一个连接是不是结束节点
            if($link['result'] == 'start' && $link['target'] == 'end') throw new Exception("开始节点的下一个流程不能是结束节点");
        }
        // 检查是否有同意审批结果
        if(!$nextNode) throw new Exception("节点缺少同意的审批结果，保存失败");

        // 流程执行次数统计
        $this->processLoop ++;
        $this->check_workflow_process($nextNode, $processData);
    }

    // 删除工作流
    public function delete_workflow(){
        $workflowId = $this->post("id");
        $workflowInfo = $this->workflowModel->get_workflow_info($workflowId);
        $this->check_data_valid($workflowInfo, true, true, true);

        // 删除菜单
        $save['is_delete'] = 1;
        $this->db->update(workflowModel::$workflowTable, $save, "id='{$workflowId}'");
        exit(json("删除工作流成功", true));
    }

    // 我发起的申请
    public function my_create(){
        $this->data['states'] = array(
            array(
                'value' => APPLICATION_PENDING,
                'title' => '待审批'
            ),
            array(
                'value' => APPLICATION_ONGOING,
                'title' => '审批中'
            ),
            array(
                'value' => APPLICATION_ACCEPTED,
                'title' => '已通过'
            ),
            array(
                'value' => APPLICATION_REJECTED,
                'title' => '已拒绝'
            )
        );
        $params['field'] = 'id, workflow_title';
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        // 只获取正常的状态
        $params['state'] = 'normal';
        $workflows = $this->workflowModel->get_workflow_list($params);
        $this->data['workflows'] = $workflows;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "my_create");
    }

    // 发起申请
    public function create(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "create");
    }

    // 查看工作流表单
    public function check_process_form($workflowId){
        $this->workflowInfo = $workflowInfo = $this->workflowModel->get_workflow_info($workflowId);
        if($workflowInfo['school_id'] != $this->rmxSchool['id'] || $workflowInfo['campus_id'] != $this->campusInfo['id']) show_error("工作流不存在，请刷新后重试");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "check_process_form");
    }

    // 查看工作流图
    public function check_process($workflowId){
        $this->workflowInfo = $workflowInfo = $this->workflowModel->get_workflow_info($workflowId);
        if($workflowInfo['school_id'] != $this->rmxSchool['id'] || $workflowInfo['campus_id'] != $this->campusInfo['id']) show_error("工作流不存在，请刷新后重试");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "check_process");
    }

    // 创建提交申请
    public function create_application($workflowId){
        $this->workflowInfo = $workflowInfo = $this->workflowModel->get_workflow_info($workflowId);
        if($workflowInfo['school_id'] != $this->rmxSchool['id'] || $workflowInfo['campus_id'] != $this->campusInfo['id']) show_error("工作流不存在，请刷新后重试");
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        // 传送workflow_id
        $this->workflow_id = $workflowId;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "create_application");
    }

    // 提交申请
    public function save_application(){
        $workflowId = $this->post('workflow_id');
        $applicationForm= $this->post('application_form');
        $userId = $this->post('user_id');
        $workflowProcess = $this->post('workflow_process');
        // 获取处理申请人id
        $handleUserId = 0;
        if($workflowProcess){
            $target = '';
            if($workflowProcess['start']){
                if($links = $workflowProcess['start']['links']){
                    foreach($links as $link){
                        if($link['result'] === 'start'){
                            $target = $link['target'];
                        } 
                    }  
                }
            }
            if($target){
                if($workflowProcess[$target]){
                    if($userinfo = $workflowProcess[$target]['approvalUser']){
                        foreach($userinfo as $key => $value){
                            $handleUserId = $key;
                            break;
                        }
                    }
                }
            }
        }
        $this->db->insert(WorkflowModel::$workflowApplicationTable, array(
            'user_id' => $userId,
            'handle_user_id' => $handleUserId,
            'workflow_id' => $workflowId,
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'state' => APPLICATION_PENDING,
            'content' => json_encode($applicationForm, JSON_UNESCAPED_UNICODE),
            'is_delete' => 0,
            'createtime' => date("Y-m-d H:i:s"),
            'updatetime' => date("Y-m-d H:i:s")
        ));
        exit(json("提交审批成功", true));
    }

    // 获取个人发起的申请
    public function get_user_application_list(){
        $workflowId = $this->get('workflowId');
        $state = $this->get('state');
        $createtime = $this->get('createtime');
        // 过滤工作流类型
        if($workflowId){
            $totalParams['workflow_id'] = $workflowId;
            $data['workflow_id'] = $workflowId;
        }
        // 过滤状态
        if($state){
            $totalParams['state'] = $state;
            $data['state'] = $state;
        }
        // 过滤发起时间
        if ($createtime){
            $totalParams['createtime'] = $createtime;
            $data['createtime'] = $createtime;
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['userId'] = $this->rmxUser['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->workflowModel->get_workflow_application_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['userId'] = $this->rmxUser['id'];
        $data['isDelete'] = 0;
        $applicationList = $this->workflowModel->get_workflow_application_list($data);
        foreach($applicationList as $key => $application){
            // 获取工作流标题
            $applicationList[$key]['workflow_title'] = '';
            $workflowId = $application['workflow_id'];
            if($workflowId){
                $workflow = $this->workflowModel->get_workflow_info($workflowId);
                $applicationList[$key]['workflow_title'] = $workflow['workflow_title'];
            }
            // 获取申请人名称
            $applicationList[$key]['handle_username'] = '';
            $handleUserId = $application['handle_user_id'];
            if($handleUserId){
                $user = $this->schoolModel->get_school_user_info_realname($handleUserId);
                $handleUsername = $user['realname'] ? $user['realname'] : $user['username'];
                $applicationList[$key]['handle_username'] = $handleUsername;
            }
            // 获取审批记录
            $applicationList[$key]['handleHistory'] = '';
            $history = $application['handle_history'];
            if($history){
                $arr = json_decode($history, true);
                $resArr = array();
                foreach($arr as $value){
                    $user = $this->schoolModel->get_school_user_info_realname($value['user_id']);
                    $username = $user['realname'] ? $user['realname'] : $user['username'];
                    if($value['action'] === 'accept'){
                        $resArr[] = $username . '已通过';
                    } else{
                        $resArr[] = $username . '已拒绝';
                    }
                }
                if($handleUserId){
                    $handleUser = $this->schoolModel->get_school_user_info_realname($handleUserId);
                    $username = $handleUser['realname'] ? $handleUser['realname'] : $handleUser['username'];
                    $resArr[] = $username . '未审批';
                }
                if(!empty($resArr)){
                    $res = implode('，', $resArr);
                    $applicationList[$key]['handleHistory'] = $res;
                }
             }
        }
        // 返回值
        exit(admin_table_data($total, $applicationList));
    }

    // 申请人查看申请内容
    public function check_application_by_user($applicationId){
        $this->applicationInfo = $this->workflowModel->get_workflow_application_info($applicationId);
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . 'workflow' . DIRECTORY_SEPARATOR . 'check_application_by_user');
    }

    // 修改申请
    public function edit_application($applicationId){
        $this->applicationInfo = $this->workflowModel->get_workflow_application_info($applicationId);
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . 'workflow' . DIRECTORY_SEPARATOR . 'edit_application');
    }

    // 提交修改申请
    public function save_edit_application($applicationId){
        $applicationForm= $this->post('application_form');
        $this->db->where('id', $applicationId);
        $this->db->update(WorkflowModel::$workflowApplicationTable, array(
            'content' => json_encode($applicationForm, JSON_UNESCAPED_UNICODE),
            'updatetime' => date("Y-m-d H:i:s")
        ));
        exit(json("修改申请成功", true));
    }

    // 删除申请
    public function delete_application(){
        $applicationId = $this->post('id');
        $this->db->where('id', $applicationId);
        $this->db->update(WorkflowModel::$workflowApplicationTable, array(
            'is_delete' => 1
        ));
        exit(json("删除申请成功", true));
    }

    // 待处理的申请
    public function my_handling(){
        $this->data['states'] = array(
            array(
                'value' => APPLICATION_PENDING,
                'title' => '待审批'
            ),
            array(
                'value' => APPLICATION_ONGOING,
                'title' => '审批中'
            ),
            array(
                'value' => APPLICATION_ACCEPTED,
                'title' => '已通过'
            ),
            array(
                'value' => APPLICATION_REJECTED,
                'title' => '已拒绝'
            )
        );
        $params['field'] = 'id, workflow_title';
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        // 只获取正常的状态
        $params['state'] = 'normal';
        $workflows = $this->workflowModel->get_workflow_list($params);
        $this->data['workflows'] = $workflows;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "my_handling");
    }

    // 获取个人待处理的申请
    public function get_handling_application_list(){
        $workflowId = $this->get('workflowId');
        $state = $this->get('state');
        $createtime = $this->get('createtime');
        // 过滤工作流类型
        if($workflowId){
            $totalParams['workflow_id'] = $workflowId;
            $data['workflow_id'] = $workflowId;
        }
        // 过滤状态
        if($state){
            $totalParams['state'] = $state;
            $data['state'] = $state;
        }
        // 过滤发起时间
        if ($createtime){
            $totalParams['createtime'] = $createtime;
            $data['createtime'] = $createtime;
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['handleUserId'] = $this->rmxUser['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->workflowModel->get_workflow_application_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['handleUserId'] = $this->rmxUser['id'];
        $data['isDelete'] = 0;
        $applicationList = $this->workflowModel->get_workflow_application_list($data);
        // 获取工作流标题
        foreach($applicationList as $key => $application){
            $applicationList[$key]['workflow_title'] = '';
            $workflowId = $application['workflow_id'];
            if($workflowId){
                $workflow = $this->workflowModel->get_workflow_info($workflowId);
                $applicationList[$key]['workflow_title'] = $workflow['workflow_title'];
            }
            $applicationList[$key]['username'] = '';
            $userId = $application['user_id'];
            if($userId){
                $user = $this->schoolModel->get_school_user_info_realname($userId);
                $username = $user['realname'] ? $user['realname'] : $user['username'];
                $applicationList[$key]['username'] = $username;
            }
        }

        // 返回值
        exit(admin_table_data($total, $applicationList));
    }

    // 已处理的申请
    public function my_handled(){
        $this->data['states'] = array(
            array(
                'value' => APPLICATION_PENDING,
                'title' => '待审批'
            ),
            array(
                'value' => APPLICATION_ONGOING,
                'title' => '审批中'
            ),
            array(
                'value' => APPLICATION_ACCEPTED,
                'title' => '已通过'
            ),
            array(
                'value' => APPLICATION_REJECTED,
                'title' => '已拒绝'
            )
        );
        $params['field'] = 'id, workflow_title';
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        // 只获取正常的状态
        $params['state'] = 'normal';
        $workflows = $this->workflowModel->get_workflow_list($params);
        $this->data['workflows'] = $workflows;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "workflow". DIRECTORY_SEPARATOR. "my_handled");
    }

    // 获取个人已处理的申请
    public function get_handled_application_list(){
        $workflowId = $this->get('workflowId');
        $state = $this->get('state');
        $createtime = $this->get('createtime');
        // 过滤工作流类型
        if($workflowId){
            $totalParams['workflow_id'] = $workflowId;
            $data['workflow_id'] = $workflowId;
        }
        // 过滤状态
        if($state){
            $totalParams['state'] = $state;
            $data['state'] = $state;
        }
        // 过滤发起时间
        if ($createtime){
            $totalParams['createtime'] = $createtime;
            $data['createtime'] = $createtime;
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['handleHistoryUserId'] = $this->rmxUser['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->workflowModel->get_workflow_application_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['handleHistoryUserId'] = $this->rmxUser['id'];
        $data['isDelete'] = 0;
        $applicationList = $this->workflowModel->get_workflow_application_list($data);
      
        foreach($applicationList as $key => $application){
            // 获取工作流标题
            $applicationList[$key]['workflow_title'] = '';
            $workflowId = $application['workflow_id'];
            if($workflowId){
                $workflow = $this->workflowModel->get_workflow_info($workflowId);
                $applicationList[$key]['workflow_title'] = $workflow['workflow_title'];
            }
            // 获取申请人
            $applicationList[$key]['username'] = '';
            $userId = $application['user_id'];
            if($userId){
                $user = $this->schoolModel->get_school_user_info_realname($userId);
                $username = $user['realname'] ? $user['realname'] : $user['username'];
                $applicationList[$key]['username'] = $username;
            }
            // 获取审批记录
            $applicationList[$key]['handle_history'] = '';
            $history = $application['handle_history'];
            if($history){
                $arr = json_decode($history, true);
                $resArr = array();
                foreach($arr as $value){
                    if($value['user_id'] === $this->rmxUser['id']){
                        if($value['action'] === 'accept'){
                            $resArr[] = '我已通过';
                        } else{
                            $resArr[] = '我已拒绝';
                        }
                    } else{
                       $user = $this->schoolModel->get_school_user_info_realname($value['user_id']);
                       $username = $user['realname'] ? $user['realname'] : $user['username'];
                       if($value['action'] === 'accept'){
                            $resArr[] = $username . '已通过';
                        } else{
                            $resArr[] = $username . '已拒绝';
                        }
                    }
                }
                if($application['handle_user_id']){
                    $handleUser = $this->schoolModel->get_school_user_info_realname($application['handle_user_id']);
                    $username = $handleUser['realname'] ? $handleUser['realname'] : $handleUser['username'];
                    $resArr[] = $username . '未审批';
                }
                if(!empty($resArr)){
                    $res = implode('，', $resArr);
                    $applicationList[$key]['handleHistory'] = $res;
                }
             }
        }

        // 返回值
        exit(admin_table_data($total, $applicationList));
    }

    // 待处理人查看申请内容
    public function check_application_by_handling_user($applicationId){
        $this->applicationInfo = $this->workflowModel->get_workflow_application_info($applicationId);
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . 'workflow' . DIRECTORY_SEPARATOR . 'check_application_by_handling_user');
    }

    // 待处理人查看申请内容
    public function check_application_by_handled_user($applicationId){
        $this->applicationInfo = $this->workflowModel->get_workflow_application_info($applicationId);
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . 'workflow' . DIRECTORY_SEPARATOR . 'check_application_by_handled_user');
    }

    // 通过申请
    public function accept_application(){
        $applicationId = $this->post('id');
        $application = $this->workflowModel->get_workflow_application_info($applicationId);
        if(empty($application)){
            throw new Exception('该申请不存在');
        }
        $workflowId = $application['workflow_id'];
        if($workflowId){
            $workflow = $this->workflowModel->get_workflow_info($workflowId);
            if($workflow){
                $process = $workflow['workflow_process'];
                $target = '';
                $this->db->where('id', $applicationId);
                if($process){
                    $processArr = json_decode($process, true);
                    foreach($processArr as $value){
                        $handleUserId = $application['handle_user_id'];
                        if(isset($value['approvalUser'][$handleUserId])){
                            if($value['links']){
                                foreach($value['links'] as $link){
                                    if($link['result'] === 'pass'){
                                        $target = $link['target'];
                                    }
                                }
                            }
                        }
                    }
                    if($target){
                        // 审批通过
                        $handleHistory = $application['handle_history'];
                        $historyArr = array();
                        if(!empty($handleHistory)){
                            $historyArr = json_decode($handleHistory, true);
                        }
                        array_push($historyArr, array('user_id' => $this->rmxUser['id'], 'action' => 'accept')); 
                        if($target === 'end'){                          
                            $this->db->update(WorkflowModel::$workflowApplicationTable, array(
                                'state' => APPLICATION_ACCEPTED,
                                'handle_history' => json_encode($historyArr, JSON_UNESCAPED_UNICODE),
                                'handle_user_id' => 0,
                                'updatetime' => date('Y-m-d H:i:s')
                            ));
                        } else{
                            // 传给下级审批
                            if($processArr[$target]){
                                $handleUserId = 0;
                                foreach($processArr[$target]['approvalUser'] as $key => $value){
                                    $handleUserId = $key;
                                    break;
                                }
                                $this->db->update(WorkflowModel::$workflowApplicationTable, array(
                                    'state' => APPLICATION_ONGOING,
                                    'handle_user_id' => $handleUserId,
                                    'handle_history' => json_encode($historyArr, JSON_UNESCAPED_UNICODE),
                                    'updatetime' => date('Y-m-d H:i:s')
                                ));
                            }
                        }
                    }
                }
            }
        }

        exit(json("通过申请成功", true));
    }

    // 拒绝申请
    public function refuse_application(){
        $applicationId = $this->post('id');
        $application = $this->workflowModel->get_workflow_application_info($applicationId);
        if(empty($application)){
            throw new Exception('该申请不存在');
        }
        $workflowId = $application['workflow_id'];
        if($workflowId){
            $workflow = $this->workflowModel->get_workflow_info($workflowId);
            if($workflow){
                $process = $workflow['workflow_process'];
                $target = '';
                $this->db->where('id', $applicationId);
                if($process){
                    $processArr = json_decode($process, true);
                    foreach($processArr as $value){
                        $handleUserId = $application['handle_user_id'];
                        if(isset($value['approvalUser'][$handleUserId])){
                            if($value['links']){
                                foreach($value['links'] as $link){
                                    if($link['result'] === 'refuse'){
                                        $target = $link['target'];
                                    }
                                }
                            }
                        }
                    }
                    if($target){
                        // 审批拒绝
                        $handleHistory = $application['handle_history'];
                        $historyArr = array();
                        if(!empty($handleHistory)){
                            $historyArr = json_decode($handleHistory, true);
                        }
                        array_push($historyArr, array('user_id' => $this->rmxUser['id'], 'action' => 'refuse')); 
                        if($target === 'end'){                          
                            $this->db->update(WorkflowModel::$workflowApplicationTable, array(
                                'state' => APPLICATION_REJECTED,
                                'handle_history' => json_encode($historyArr, JSON_UNESCAPED_UNICODE),
                                'handle_user_id' => 0,
                                'updatetime' => date('Y-m-d H:i:s')
                            ));
                        } else{
                            // 传给上级领导审批
                            if($processArr[$target]){
                                $handleUserId = 0;
                                foreach($processArr[$target]['approvalUser'] as $key => $value){
                                    $handleUserId = $key;
                                    break;
                                }
                                $this->db->update(WorkflowModel::$workflowApplicationTable, array(
                                    'state' => APPLICATION_ONGOING,
                                    'handle_user_id' => $handleUserId,
                                    'handle_history' => json_encode($historyArr, JSON_UNESCAPED_UNICODE),
                                    'updatetime' => date('Y-m-d H:i:s')
                                ));
                            }
                        }
                    }
                }
            }
        }

        exit(json("拒绝申请成功", true));
    }
}